#!/usr/bin/env python
# -*- coding: utf-8 -*-

from typing import List, Dict, Any, Optional, Literal

from fastapi import APIRouter, Depends, HTTPException, Query, Path
from fastapi.responses import JSONResponse

from app.core.dependencies import get_services
from app.core.exceptions import NotFoundError, DatabaseError, EmbeddingError, VectorDBError
from app.models.api import (
    TrainingDataCreate,
    TrainingDataResponse,
    TrainingDataFilter,
    MessageResponse,
    PaginatedResponse
)

# 创建路由
router = APIRouter()


@router.post("/{project_id}/training-data", response_model=TrainingDataResponse)
async def create_training_data(
    training_data: TrainingDataCreate,
    project_id: str = Path(..., description="项目ID"),
    services=Depends(get_services)
):
    """创建训练数据"""
    try:
        data_dict = await services["training_data_service"].add_training_data(
            project_id=project_id,
            data_type=training_data.type,
            content=training_data.content,
            question=training_data.question,
            sql=training_data.sql
        )
        return data_dict
    except NotFoundError as e:
        raise HTTPException(status_code=404, detail=str(e))
    except (DatabaseError, EmbeddingError, VectorDBError) as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/{project_id}/training-data", response_model=PaginatedResponse)
async def list_training_data(
    project_id: str = Path(..., description="项目ID"),
    type: Optional[Literal["ddl", "question_sql", "description"]] = Query(None, description="数据类型"),
    limit: int = Query(10, ge=1, le=100),
    offset: int = Query(0, ge=0),
    services=Depends(get_services)
):
    """列出训练数据"""
    try:
        data_list, total = await services["training_data_service"].list_training_data(
            project_id=project_id,
            data_type=type,
            limit=limit,
            offset=offset
        )
        
        # 数据已经是字典格式，直接使用
        return {
            "items": data_list,
            "total": total,
            "limit": limit,
            "offset": offset
        }
    except DatabaseError as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/{project_id}/training-data/{data_id}", response_model=TrainingDataResponse)
async def get_training_data(
    project_id: str = Path(..., description="项目ID"),
    data_id: int = Path(..., description="训练数据ID"),
    services=Depends(get_services)
):
    """获取训练数据"""
    try:
        data_dict = await services["training_data_service"].get_training_data(data_id)
        
        # 检查项目ID是否匹配
        if data_dict["project_id"] != project_id:
            raise HTTPException(status_code=404, detail="训练数据不存在或不属于指定项目")
        
        return data_dict
    except NotFoundError as e:
        raise HTTPException(status_code=404, detail=str(e))
    except DatabaseError as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.delete("/{project_id}/training-data/{data_id}", response_model=MessageResponse)
async def delete_training_data(
    project_id: str = Path(..., description="项目ID"),
    data_id: int = Path(..., description="训练数据ID"),
    services=Depends(get_services)
):
    """删除训练数据"""
    try:
        # 先获取训练数据，检查项目ID是否匹配
        data = await services["training_data_service"].get_training_data(data_id)
        
        # 处理字典或对象
        data_project_id = data["project_id"] if isinstance(data, dict) else data.project_id
        
        if data_project_id != project_id:
            raise HTTPException(status_code=404, detail="训练数据不存在或不属于指定项目")
        
        await services["training_data_service"].delete_training_data(data_id)
        return {"message": f"训练数据 {data_id} 已删除"}
    except NotFoundError as e:
        raise HTTPException(status_code=404, detail=str(e))
    except (DatabaseError, VectorDBError) as e:
        raise HTTPException(status_code=500, detail=str(e))